<?php

namespace App\Service\OpenShop\FeishuMini;

use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Models\Common\ResourcesModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\Wanggui\CustomerDepartmentClueRecordModel;
use App\Models\Wanggui\CustomerDepartmentDevelopmentManagerModel;
use App\Models\Wanggui\CustomerDepartmentFollowUpRecordModel;
use App\Models\Wanggui\CustomerDepartmentKpPartyRecordModel;
use App\Models\Wanggui\CustomerDepartmentOperationLogModel;
use App\Models\Wanggui\CustomerDepartmentSiteLocationRelationModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Service\BaseService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use App\Service\OpenShop\SiteLocation\SiteLocationService;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CustomerDepartmentService extends BaseService
{


    /**
     * @param int $id
     * @param int $taskId
     * @param int $status
     * @param string $preHaving
     * @param string $content
     * @param int $berthCount
     * @param array $authUser
     * @return array
     */
    public static function addClue(int $id, int $taskId, int $status, string $preHaving, string $content, int $berthCount, array $authUser): array
    {
        $taskModel = CustomerDepartmentTaskModel::query()
            ->where('id', $taskId)
            ->first();

        if (null == $taskModel) {
            self::throwErr('关联的任务不存在', 404);
        }

        // 跟新线索的信息
        $updateTaskParams['updatedByUid'] = $authUser['userId'] ?? 0;
        if ($id) {
            $clueRecordModel = CustomerDepartmentClueRecordModel::query()->where('id', $id)->first();
            if (null == $clueRecordModel) {
                self::throwErr('要修改的线索不存在', 404);
            }
            $logTitle = '修改点位线索状态';
            $changes  = [
                [
                    'theme' => '线索状态变更',
                    'data'  => [
                        [
                            'key'         => 'status',
                            'beforeValue' => $clueRecordModel->status,
                            'afterValue'  => $status,
                            'beforeText'  => CustomerDepartmentClueRecordModel::STATUS_MAPPING[$clueRecordModel->status] ?? '',
                            'afterText'   => CustomerDepartmentClueRecordModel::STATUS_MAPPING[$status] ?? '',
                            'type'        => 1,
                            'description' => '线索状态',
                        ]
                    ]
                ]
            ];
        } else {
            $clueRecordModel               = new CustomerDepartmentClueRecordModel();
            $clueRecordModel->taskId       = $taskId;
            $clueRecordModel->wgNumber     = $taskModel->wgNumber;
            $clueRecordModel->wgType       = $taskModel->wgType;
            $clueRecordModel->berthCount   = $berthCount;
            $clueRecordModel->preHaving    = $updateTaskParams['preHaving'] = Carbon::createFromDate($preHaving)->endOfDay()->timestamp;
            $clueRecordModel->content      = $content;
            $clueRecordModel->createdByUid = $authUser['userId'] ?? 0;
            $logTitle                      = '新增点位线索';
            $changes                       = [
                [
                    'theme' => '点位线索',
                    'data'  => [
                        [
                            'key'         => 'status',
                            'beforeValue' => '',
                            'afterValue'  => $status,
                            'beforeText'  => '',
                            'afterText'   => CustomerDepartmentClueRecordModel::STATUS_MAPPING[$status] ?? '',
                            'type'        => 1,
                            'description' => '线索状态',
                        ], [
                            'key'         => 'preHaving',
                            'beforeValue' => '',
                            'afterValue'  => $preHaving,
                            'beforeText'  => '',
                            'afterText'   => $preHaving,
                            'type'        => 1,
                            'description' => '预计出铺时间',
                        ], [
                            'key'         => 'berthCount',
                            'beforeValue' => '',
                            'afterValue'  => $berthCount,
                            'beforeText'  => '',
                            'afterText'   => $berthCount,
                            'type'        => 1,
                            'description' => '铺位数量',
                        ], [
                            'key'         => 'content',
                            'beforeValue' => '',
                            'afterValue'  => $content,
                            'beforeText'  => '',
                            'afterText'   => $content,
                            'type'        => 1,
                            'description' => '线索信息',
                        ]
                    ]
                ]
            ];
        }
        $clueRecordModel->status       = $status;
        $clueRecordModel->updatedByUid = $authUser['userId'] ?? 0;
        $clueRecordModel->save();


        // 更新项目进度
        CustomerDepartmentTaskModel::query()
            ->where('id', $taskId)
            ->update(
                array_merge(
                    $updateTaskParams,
                    ($id ? ['projectPhase' => self::getProjectPhaseByTaskId($taskId)] : []
                    )
                )
            );

        Artisan::call("siteLocation:sync-development-manager-task-info --rmsUserIds={$authUser['userId']}");


        // 添加日志
        CustomerDepartmentOperationLogModel::addLog($taskId, $logTitle, $changes, $authUser['userId']);


        return [
            'id'    => $clueRecordModel->id,
            'title' => Carbon::createFromDate($preHaving)->format('预计Y年m月d日出铺'),
        ];
    }


    /**
     * 线索列表
     * @param int $pageSize
     * @param int $pageNum
     * @param string $searchText
     * @param array $authUser
     * @param int $taskId
     * @return array
     */
    public static function clue(int $pageSize, int $pageNum, string $searchText, array $authUser, int $taskId = 0): array
    {
        $paginator = CustomerDepartmentClueRecordModel::query()
            ->orderByDesc('id')
            ->when($taskId, function ($query) use ($taskId) {
                $query->where('taskId', $taskId);
            })
            ->when(mb_strlen($searchText), function ($query) use ($searchText) {
                $query->where('content', 'like', "%{$searchText}%");
            })
            ->with(['followUpRel'])
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $userIds = [];

        $list = $paginator->map(function ($item) use (&$userIds) {
            $userIds    = array_merge($userIds, $item->followUpRel->pluck('createdByUid')->toArray());
            $firstTime  = '-';
            $lastTime   = '-';
            $lastUserId = 0;
            if (count($item->followUpRel)) {
                $firstTime  = $item->followUpRel->first()->createdAt->format('Y-m-d');
                $lastTime   = $item->followUpRel->last()->createdAt->format('Y-m-d');
                $lastUserId = $item->followUpRel->last()->createdByUid;
            }

            return [
                'id'        => $item->id,
                'status'    => $item->status,
                'statusStr' => CustomerDepartmentClueRecordModel::STATUS_MAPPING[$item->status] ?? '-',
                'title'     => Carbon::createFromTimestamp($item->preHaving)->format('预计Y年m月d日出铺'),
                'firstTime' => $firstTime,
                'lastTime'  => $lastTime,
                'logCount'  => count($item->followUpRel),
                'username'  => '',
                'userId'    => $lastUserId,
                'content'   => $item->content,
            ];
        });

        $userInfos = [];
        KmsUser::query()
            ->whereIn('rmsUserId', $userIds)
            ->get()
            ->each(function (KmsUser $kmsUser) use (&$userInfos) {
                if ($kmsUser->rmsUserId != 0) {
                    $userInfos[$kmsUser->rmsUserId] = $kmsUser->nickname . '(' . $kmsUser->name . ')';
                }
            });


        return [
            'count'    => $paginator->total(),
            'list'     => collect($list)->map(function ($item) use ($userInfos) {
                $item['username'] = $userInfos[$item['userId']] ?? '-';
                return $item;
            }),
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }


    /**
     * 获得跟进记录
     * @param int $pageSize
     * @param int $pageNum
     * @param array $authUser
     * @param int $taskId
     * @return array
     */
    public static function followUp(int $pageSize, int $pageNum, array $authUser, int $taskId = 0): array
    {
        $paginator = CustomerDepartmentFollowUpRecordModel::query()
            ->where('createdByUid', $authUser['userId'])
            ->orderByDesc('id')
            ->when($taskId, function ($query) use ($taskId) {
                $query->where('taskId', $taskId);
            })
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $userIds   = $paginator->pluck('createdByUid')->toArray();
        $userInfos = [];
        KmsUser::query()
            ->whereIn('rmsUserId', $userIds)
            ->get()
            ->each(function (KmsUser $kmsUser) use (&$userInfos) {
                if ($kmsUser->rmsUserId != 0) {
                    $userInfos[$kmsUser->rmsUserId] = $kmsUser->nickname . '(' . $kmsUser->name . ')';
                }
            });

        $list = $paginator->map(function ($item) use ($userInfos) {
            return [
                'id'        => $item->id,
                'createdAt' => $item->createdAt->format('Y-m-d H:i:s'),
                'username'  => $userInfos[$item->createdByUid] ?? '-',
                'content'   => $item->content,
                'typeStr'   => CustomerDepartmentFollowUpRecordModel::TYPE_MAPPING[$item->type] ?? '',
                'type'      => $item->type,
            ];
        });


        return [
            'count'    => $paginator->total(),
            'list'     => $list,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }

    /**
     * 线索详情
     * @param int $id
     * @param array $authUser
     * @return array
     */
    public static function detailClue(int $id, array $authUser): array
    {
        $clueRecordModel = CustomerDepartmentClueRecordModel::query()
            ->where('id', $id)
            ->with(['followUpRel', 'taskRel'])
            ->first();

        if (null == $clueRecordModel) {
            self::throwErr('要查询的线索不存在', 404);
        }

        $userIds[]          = $clueRecordModel->createdByUid;
        $followUpRecord     = [];  // 跟进日志
        $lastFollowUpUserId = 0;   // 最后的跟进人

        foreach ($clueRecordModel->followUpRel as $followUp) {
            $userIds[]          = $followUp->createdByUid;
            $lastFollowUpUserId = $followUp->createdByUid;

            array_unshift($followUpRecord, [
                'typeStr' => CustomerDepartmentFollowUpRecordModel::TYPE_MAPPING[$followUp->type] ?? '',
                'id'      => $followUp->id,
                'type'    => $followUp->type,
                'userId'  => $followUp->createdByUid,
                'content' => $followUp->content,
                'time'    => $followUp->createdAt->format('Y-m-d H:i')
            ]);
        }

        KmsUser::query()
            ->whereIn('rmsUserId', $userIds)
            ->get()
            ->each(function (KmsUser $kmsUser) use (&$userInfos) {
                if ($kmsUser->rmsUserId != 0) {
                    $userInfos[$kmsUser->rmsUserId] = $kmsUser->nickname . '(' . $kmsUser->name . ')';
                }
            });

        return [
            'wgName'           => (string)optional($clueRecordModel->taskRel)->wgName,
            'grade'            => (int)optional($clueRecordModel->taskRel)->grade,
            'gradeStr'         => CustomerDepartmentTaskModel::GRADE_MAPPING[(int)optional($clueRecordModel->taskRel)->grade] ?? '',
            'content'          => $clueRecordModel->content,
            'preHaving'        => Carbon::createFromTimestamp($clueRecordModel->preHaving)->toDateString(),
            'berthCount'       => $clueRecordModel->berthCount ?: '-',
            'id'               => $clueRecordModel->id,
            'statusStr'        => CustomerDepartmentClueRecordModel::STATUS_MAPPING[$clueRecordModel->status] ?? '',
            'status'           => $clueRecordModel->status,
            'recordUsername'   => $userInfos[$clueRecordModel->createdByUid] ?? '-',
            'followUpUsername' => $userInfos[$lastFollowUpUserId] ?? '-',
            'followRecord'     => collect($followUpRecord)->map(function ($item) use ($userInfos) {
                $item['username'] = $userInfos[$item['userId']] ?? '-';
                return $item;
            })->values()->toArray(),
        ];


    }


    /**
     * 添加客户
     * @param int $id
     * @param int $taskId
     * @param string $name
     * @param string $phone
     * @param string $wechatCode
     * @param int $gender
     * @param string $prefixAddress
     * @param int $provinceCode
     * @param int $cityCode
     * @param int $districtCode
     * @param string $company
     * @param int $companyType
     * @param int $type
     * @param int $isOnTheJob
     * @param string $position
     * @param string $remark
     * @param array $authUser
     * @return array
     */
    public static function addDock(int $id, int $taskId, string $name, string $phone, string $wechatCode, int $gender, string $prefixAddress, int $provinceCode, int $cityCode, int $districtCode, string $company, int $companyType, int $type, int $isOnTheJob, string $position, string $remark, array $authUser): array
    {

        $taskModel = CustomerDepartmentTaskModel::query()
            ->where('id', $taskId)
            ->first();

        if (null == $taskModel) {
            self::throwErr('关联的任务不存在', 404);
        }

        $oldKpParty = null;
        if ($id) {
            $kpPartyModel = CustomerDepartmentKpPartyRecordModel::query()->where('id', $id)->first();
            $oldKpParty   = clone $kpPartyModel;
            if (null == $kpPartyModel) {
                self::throwErr('要修改的客户不存在', 404);
            }
            $logTitle = '修改甲方信息';
        } else {
            $kpPartyModel               = new CustomerDepartmentKpPartyRecordModel();
            $kpPartyModel->createdByUid = $authUser['userId'] ?? '';
            $logTitle                   = '新增甲方信息';
        }

        $kpPartyModel->taskId        = $taskId;
        $kpPartyModel->name          = $name;
        $kpPartyModel->wgNumber      = $taskModel->wgNumber;
        $kpPartyModel->wgType        = $taskModel->wgType;
        $kpPartyModel->phone         = $phone;
        $kpPartyModel->id            = $id;
        $kpPartyModel->wechatCode    = $wechatCode;
        $kpPartyModel->gender        = $gender;
        $kpPartyModel->prefixAddress = $prefixAddress;
        $kpPartyModel->provinceCode  = $provinceCode;
        $kpPartyModel->cityCode      = $cityCode;
        $kpPartyModel->districtCode  = $districtCode;
        $kpPartyModel->company       = $company;
        $kpPartyModel->companyType   = $companyType;
        $kpPartyModel->type          = $type;
        $kpPartyModel->onTheJob      = $isOnTheJob;
        $kpPartyModel->position      = $position;
        $kpPartyModel->remark        = $remark;
        $kpPartyModel->updatedByUid  = $authUser['userId'] ?? 0;
        $kpPartyModel->save();

        // 更新项目修改人
        CustomerDepartmentTaskModel::query()
            ->where('id', $taskId)
            ->update([
                'updatedByUid' => $authUser['userId'] ?? 0
            ]);

        CustomerDepartmentOperationLogModel::addLog($taskId, $logTitle, [
            [
                'theme' => '甲方信息',
                'data'  => [
                    [
                        'key'         => 'name',
                        'beforeValue' => (string)optional($oldKpParty)->name,
                        'afterValue'  => $name,
                        'beforeText'  => (string)optional($oldKpParty)->name,
                        'afterText'   => $name,
                        'type'        => 1,
                        'description' => '甲方姓名',
                    ],
                    [
                        'key'         => 'phone',
                        'beforeValue' => (string)optional($oldKpParty)->phone,
                        'afterValue'  => $phone,
                        'beforeText'  => (string)optional($oldKpParty)->phone,
                        'afterText'   => $phone,
                        'type'        => 1,
                        'description' => '手机号码',
                    ],
                    [
                        'key'         => 'wechatCode',
                        'beforeValue' => (string)optional($oldKpParty)->wechatCode,
                        'afterValue'  => $wechatCode,
                        'beforeText'  => (string)optional($oldKpParty)->wechatCode,
                        'afterText'   => $wechatCode,
                        'type'        => 1,
                        'description' => '微信号',
                    ],
                    [
                        'key'         => 'gender',
                        'beforeValue' => (int)optional($oldKpParty)->gender,
                        'afterValue'  => $gender,
                        'beforeText'  => (string)optional($oldKpParty)->gender ? (CustomerDepartmentKpPartyRecordModel::GENDER_MAPPING[$oldKpParty->gender] ?? '') : '',
                        'afterText'   => $gender ? (CustomerDepartmentKpPartyRecordModel::GENDER_MAPPING[$gender] ?? '') : '',
                        'type'        => 1,
                        'description' => '甲方性别',
                    ],
                    [
                        'key'         => 'type',
                        'beforeValue' => (int)optional($oldKpParty)->type,
                        'afterValue'  => $type,
                        'beforeText'  => (string)optional($oldKpParty)->type ? (CustomerDepartmentKpPartyRecordModel::TYPE_MAPPING[$oldKpParty->type] ?? '') : '',
                        'afterText'   => $type ? (CustomerDepartmentKpPartyRecordModel::TYPE_MAPPING[$type] ?? '') : '',
                        'type'        => 1,
                        'description' => '甲方类别',
                    ],
                    [
                        'key'         => 'prefixAddress',
                        'beforeValue' => (string)optional($oldKpParty)->prefixAddress,
                        'afterValue'  => $prefixAddress,
                        'beforeText'  => (string)optional($oldKpParty)->prefixAddress,
                        'afterText'   => $prefixAddress,
                        'type'        => 1,
                        'description' => '所在城市',
                    ],
                    [
                        'key'         => 'company',
                        'beforeValue' => (string)optional($oldKpParty)->company,
                        'afterValue'  => $company,
                        'beforeText'  => (string)optional($oldKpParty)->company,
                        'afterText'   => $company,
                        'type'        => 1,
                        'description' => '所属公司',
                    ],
                    [
                        'key'         => 'companyType',
                        'beforeValue' => (int)optional($oldKpParty)->companyType,
                        'afterValue'  => $companyType,
                        'beforeText'  => (string)optional($oldKpParty)->companyType ? (CustomerDepartmentKpPartyRecordModel::COMPANY_TYPE_MAPPING[$oldKpParty->companyType] ?? '') : '',
                        'afterText'   => $companyType ? (CustomerDepartmentKpPartyRecordModel::COMPANY_TYPE_MAPPING[$companyType] ?? '') : '',
                        'type'        => 1,
                        'description' => '公司类型',
                    ],
                    [
                        'key'         => 'onTheJob',
                        'beforeValue' => (int)optional($oldKpParty)->onTheJob,
                        'afterValue'  => $isOnTheJob,
                        'beforeText'  => (string)optional($oldKpParty)->onTheJob ? (CustomerDepartmentKpPartyRecordModel::IS_ON_THE_JOB_MAPPING[$oldKpParty->onTheJob] ?? '') : '',
                        'afterText'   => $isOnTheJob ? (CustomerDepartmentKpPartyRecordModel::IS_ON_THE_JOB_MAPPING[$isOnTheJob] ?? '') : '',
                        'type'        => 1,
                        'description' => '是否在职',
                    ],
                    [
                        'key'         => 'position',
                        'beforeValue' => (string)optional($oldKpParty)->position,
                        'afterValue'  => $position,
                        'beforeText'  => (string)optional($oldKpParty)->position,
                        'afterText'   => $position,
                        'type'        => 1,
                        'description' => '所在职位',
                    ],
                    [
                        'key'         => 'remark',
                        'beforeValue' => (string)optional($oldKpParty)->remark,
                        'afterValue'  => $remark,
                        'beforeText'  => (string)optional($oldKpParty)->remark,
                        'afterText'   => $remark,
                        'type'        => 1,
                        'description' => '备注',
                    ]
                ]
            ]
        ], $authUser['userId']);

        return [
            'id'    => $kpPartyModel->id,
            'name'  => $kpPartyModel->name,
            'phone' => $kpPartyModel->phone,
        ];
    }

    /**
     * 客户列表
     * @param int $pageSize
     * @param int $pageNum
     * @param string $name
     * @param string $phone
     * @param array $authUser
     * @return array
     */
    public static function dock(int $pageSize, int $pageNum, string $name, string $phone, array $authUser): array
    {
        $paginator = CustomerDepartmentKpPartyRecordModel::query()
            ->where('createdByUid', $authUser['userId'])
            ->when(mb_strlen($name), function ($query) use ($name) {
                $query->where('name', 'like', "%{$name}%");
            })
            ->when(mb_strlen($phone), function ($query) use ($phone) {
                $query->where('phone', $phone);
            })
            ->orderByDesc('updatedAt')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $userIds   = $paginator->pluck('createdByUid')->toArray();
        $userInfos = [];
        KmsUser::query()
            ->whereIn('rmsUserId', $userIds)
            ->get()
            ->each(function (KmsUser $kmsUser) use (&$userInfos) {
                if ($kmsUser->rmsUserId != 0) {
                    $userInfos[$kmsUser->rmsUserId] = $kmsUser->nickname . '(' . $kmsUser->name . ')';
                }
            });

        $list = $paginator->map(function ($item) use ($userInfos) {
            return [
                'id'            => $item->id,
                'name'          => $item->name,
                'phone'         => $item->phone,
                'position'      => $item->position,
                'prefixAddress' => $item->prefixAddress,
                'createdAt'     => $item->createdAt->format('Y-m-d H:i:s'),
                'username'      => $userInfos[$item->createdByUid] ?? '-',
                'updatedAt'     => $item->updatedAt->format('Y-m-d H:i:s')
            ];
        });

        return [
            'count'    => $paginator->total(),
            'list'     => $list,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }


    /**
     * 新增跟进记录
     * @param int $taskId
     * @param int $type
     * @param int $method
     * @param array $files
     * @param string $content
     * @param int $kpPartyId
     * @param int $clueId
     * @param array $authUser
     * @return void
     */
    public static function addFollowUp(int $taskId, int $type, int $method, array $files, string $content, int $kpPartyId, int $clueId, array $authUser)
    {

        $followUpModel               = new CustomerDepartmentFollowUpRecordModel();
        $followUpModel->type         = $type;
        $followUpModel->taskId       = $taskId;
        $followUpModel->method       = $method;
        $followUpModel->content      = $content;
        $followUpModel->kpPartyId    = $kpPartyId;
        $followUpModel->clueId       = $clueId;
        $followUpModel->createdByUid = $authUser['userId'] ?? 0;
        $followUpModel->updatedByUid = $authUser['userId'] ?? 0;
        $followUpModel->save();


        // 更新项目进度
        CustomerDepartmentTaskModel::query()
            ->where('id', $taskId)
            ->update([
                'projectPhase' => self::getProjectPhaseByTaskId($taskId),
                'followUpTime' => time(),
                'updatedByUid' => $authUser['userId'] ?? 0
            ]);

        // 修改开发经理的跟进时间
        CustomerDepartmentDevelopmentManagerModel::query()
            ->where('rmsUserId', ($authUser['userId'] ?? 0))
            ->update([
                'followUpTime' => time()
            ]);

        $kpPartyName  = '';
        $kpPartyPhone = '';
        if ($kpPartyId) {
            // 修改客户的跟进时间
            $kpPartyModel = CustomerDepartmentKpPartyRecordModel::query()
                ->where('id', $kpPartyId);
            $kpPartyName  = (clone $kpPartyModel)->value('name');
            $kpPartyPhone = (clone $kpPartyModel)->value('phone');
            $kpPartyModel->update([
                'followUpTime' => time()
            ]);
        }

        $clueName = '';
        if ($clueId) {
            // 修改线索的跟进时间
            $clueModel = CustomerDepartmentClueRecordModel::query()
                ->where('id', $clueId);
            $clueName  = Carbon::createFromTimestamp((clone $clueModel)->value('preHaving'))->format('预计Y年m月d日出铺');
            $clueModel->update([
                'followUpTime' => time()
            ]);
        }

        $insertData = [];
        foreach ($files as $file) {
            $insertData[] = [
                'businessId'   => $followUpModel->id,
                'module'       => ResourcesModel::MODULE_TYPE_COMMUNICATE_RECORD,
                'business'     => ResourcesModel::BUSINESS_COMMUNICATE_RECORD,
                'name'         => 'communicateRecord',
                'url'          => ltrim(parse_url($file, PHP_URL_PATH), '/'),
                'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                'createdAt'    => time(),
                'updatedAt'    => time(),
                'createdByUid' => $authUser['userId'] ?? 0,
                'updatedByUid' => $authUser['userId'] ?? 0,
            ];
        }

        //添加资源
        ResourcesModel::query()->insert($insertData);

        Artisan::call("siteLocation:sync-development-manager-task-info --rmsUserIds={$authUser['userId']}");


        CustomerDepartmentOperationLogModel::addLog($taskId, '新增跟进记录', [
            [
                'theme' => '跟进记录',
                'data'  => [
                    [
                        'key'         => 'type',
                        'beforeValue' => '',
                        'afterValue'  => $type,
                        'beforeText'  => '',
                        'afterText'   => CustomerDepartmentFollowUpRecordModel::TYPE_MAPPING[$type] ?? '',
                        'type'        => 1,
                        'description' => '跟进类型',
                    ],
                    [
                        'key'         => 'method',
                        'beforeValue' => '',
                        'afterValue'  => $method,
                        'beforeText'  => '',
                        'afterText'   => CustomerDepartmentFollowUpRecordModel::METHOD_MAPPING[$method] ?? '',
                        'type'        => 1,
                        'description' => '跟进方式',
                    ],
                    [
                        'key'         => 'file',
                        'beforeValue' => '',
                        'afterValue'  => $files,
                        'beforeText'  => '',
                        'afterText'   => $files,
                        'type'        => 9,
                        'description' => '跟进截图',
                    ],
                    [
                        'key'         => 'content',
                        'beforeValue' => '',
                        'afterValue'  => $content,
                        'beforeText'  => '',
                        'afterText'   => $content,
                        'type'        => 1,
                        'description' => '跟进记录',
                    ],
                    [
                        'key'         => 'clueName',
                        'beforeValue' => '',
                        'afterValue'  => $clueName,
                        'beforeText'  => '',
                        'afterText'   => $clueName,
                        'type'        => 1,
                        'description' => '关联线索名称',
                    ],
                    [
                        'key'         => 'kpPartyName',
                        'beforeValue' => '',
                        'afterValue'  => $kpPartyName,
                        'beforeText'  => '',
                        'afterText'   => $kpPartyName,
                        'type'        => 1,
                        'description' => '关联甲方名称',
                    ],
                    [
                        'key'         => 'kpPartyPhone',
                        'beforeValue' => '',
                        'afterValue'  => $kpPartyPhone,
                        'beforeText'  => '',
                        'afterText'   => $kpPartyPhone,
                        'type'        => 1,
                        'description' => '关联甲方手机号',
                    ]
                ]
            ]
        ], $authUser['userId']);
    }

    /**
     * 获得任务清单
     * @param int $pageSize
     * @param int $pageNum
     * @param $authUser
     * @return array
     */
    public static function site(int $pageSize, int $pageNum, $authUser): array
    {
        $paginator = CustomerDepartmentTaskModel::query()
            ->where('assignId', $authUser['userId'])
            ->with(['followUpRel'])
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $userIds   = $paginator->pluck('assignId')->toArray();
        $userInfos = [];
        KmsUser::query()
            ->whereIn('rmsUserId', $userIds)
            ->get()
            ->each(function (KmsUser $kmsUser) use (&$userInfos) {
                if ($kmsUser->rmsUserId != 0) {
                    $userInfos[$kmsUser->rmsUserId] = $kmsUser->nickname . '(' . $kmsUser->name . ')';
                }
            });

        $list = $paginator->map(function ($item) use ($userInfos) {
            $followUpTime = '-';

            if (count($item->followUpRel)) {
                $followUpTime = $item->followUpRel->last()->createdAt->format('Y-m-d H:i:s');
            }

            return [
                'id'           => $item->id,
                'name'         => $item->wgName,
                'address'      => $item->address,
                'assignTime'   => Carbon::createFromTimestamp($item->assignTime)->format('Y-m-d H:i:s'),
                'username'     => $userInfos[$item->assignId] ?? '-',
                'followUpTime' => $followUpTime
            ];
        });

        return [
            'count'    => $paginator->total(),
            'list'     => $list,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }


    /**
     * 调整点位模型内不统一的字段 (暂停)
     * @param $model
     * @param $wgType
     */
    public static function adjustPoiModel($model, $wgType)
    {
        switch ($wgType) {
            case CustomerDepartmentTaskModel::WG_TYPE_MALL:
                $model->name = $model->mallName;
                break;
            //case CustomerDepartmentTaskModel::WG_TYPE_STREET:
            //    break;
            //case CustomerDepartmentTaskModel::WG_TYPE_UNIVERSITY:
            //    break;
            //case CustomerDepartmentTaskModel::WG_TYPE_PARK:
            //    break;
            //case CustomerDepartmentTaskModel::WG_TYPE_TOWN:
            //    break;
            default:
                self::throwErr('网规类型不存在', 404);
        }

        return $model;
    }


    /**
     * 任务详情
     * @param int $id
     * @param $authUser
     * @return array
     * @throws GuzzleException
     */
    public static function detailSite(int $id, $authUser): array
    {
        $taskModel = CustomerDepartmentTaskModel::query()
            ->where('id', $id)
            ->with(['followUpRel.kpPartyRel', 'kpPartyRel', 'clueRel.followUpRel', 'siteLocationMallRel'])
            ->first();

        if (null == $taskModel) {
            self::throwErr('任务不存在', 404);
        }

        $userIds = [$taskModel->assignId];

        $kpPartyName  = ''; // 最新甲方名称
        $kpPartyPhone = ''; // 最新甲方手机
        $followRecord = [];

        if (count($taskModel->followUpRel)) {
            foreach ($taskModel->followUpRel as $followUpRel) {
                $userIds[] = $followUpRel->createdByUid;
                array_unshift($followRecord, [
                    'id'        => $followUpRel->id,
                    'createdAt' => $followUpRel->createdAt->format('Y-m-d H:i:s'),
                    'userId'    => $followUpRel->createdByUid,
                    'content'   => $followUpRel->content,
                    'typeStr'   => CustomerDepartmentFollowUpRecordModel::TYPE_MAPPING[$followUpRel->type] ?? '',
                    'type'      => $followUpRel->type,
                    'username'  => '',
                ]);
            }
            // 最新的客户名称
            $kpPartyName  = implode(
                '·', array_merge(
                    (optional($taskModel->followUpRel->last()->kpPartyRel)->name ? [$taskModel->followUpRel->last()->kpPartyRel->name] : []),
                    (optional($taskModel->followUpRel->last()->kpPartyRel)->position ? [$taskModel->followUpRel->last()->kpPartyRel->position] : []),
                )
            );
            $kpPartyPhone = optional($taskModel->followUpRel->last()->kpPartyRel)->phone;
        }


        $clueRecord = [];
        if (count($taskModel->clueRel)) {
            foreach ($taskModel->clueRel as $clueRel) {
                $userIds[]  = $clueRel->createdByUid;
                $firstTime  = '-';
                $lastTime   = '-';
                $lastUserId = 0;
                if (count($clueRel->followUpRel)) {
                    $firstTime  = $clueRel->followUpRel->first()->createdAt->format('Y-m-d');
                    $lastTime   = $clueRel->followUpRel->last()->createdAt->format('Y-m-d');
                    $lastUserId = $clueRel->followUpRel->last()->createdByUid;
                }
                $clueRecord[] = [
                    'id'        => $clueRel->id,
                    'status'    => $clueRel->status,
                    'statusStr' => CustomerDepartmentClueRecordModel::STATUS_MAPPING[$clueRel->status] ?? '-',
                    'title'     => Carbon::createFromTimestamp($clueRel->preHaving)->format('预计Y年m月d日出铺'),
                    'firstTime' => $firstTime,
                    'lastTime'  => $lastTime,
                    'logCount'  => count($clueRel->followUpRel),
                    'username'  => '',
                    'userId'    => $lastUserId,
                    'content'   => $clueRel->content,
                ];
            }
        }


        //获得观远的数据
        try {
            $guanyuanData = array_column(GuanyuanDataService::getMallDataByCity([$taskModel->siteLocationMallRel->mallId]), null, '商场ID');
        } catch (\Exception $exception) {
            $guanyuanData = [];
        }


        $relationModel = CustomerDepartmentSiteLocationRelationModel::query()
            ->where('taskId', $taskModel->id);


        // 获得房源信息
        $houseList = OpenShopSiteLocationModel::query()
            ->whereIn(
                'id',
                (clone $relationModel)
                    ->where('source', OpenShopSiteLocationModel::SOURCE_HOUSING)
                    ->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)
                    ->pluck('relationId')
                    ->toArray()
            )
            ->with(['uploadFileResourceRel'])
            ->get()
            ->map(function (OpenShopSiteLocationModel $openShopSiteLocationModel) use (&$userIds) {
                $userIds[] = $openShopSiteLocationModel->createdByUid;
                if (count($openShopSiteLocationModel->uploadFileResourceRel)) {
                    $image = $openShopSiteLocationModel->uploadFileResourceRel[0]->formatUrl ?? '';
                    foreach ($openShopSiteLocationModel->uploadFileResourceRel as $value) {
                        if ($value->position == UploadFileResourceEnum::SHOP_ADDRESS_FRONT_PHOTO) {
                            $image = $value->formatUrl;
                        }
                    }
                } else {
                    $image = 'https://file.51kuafu.com/52/42/6f191617b85d80427702dcf6e938872fa6bbb4552898631ca5a13787bdab.png'; //添加默认图片
                }

                $cityAreaArr = explode('-', $openShopSiteLocationModel->cityArea);
                if (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1]) && isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1] . '-' . $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2];
                } elseif (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1];
                } elseif (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2];
                } else {
                    $cityArea = '';
                }

                return [
                    'id'            => $openShopSiteLocationModel->id,
                    'orderNo'       => $openShopSiteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_6 ? 'FY' . $openShopSiteLocationModel->id : $openShopSiteLocationModel->orderNo,
                    'image'         => $image,
                    'address'       => $openShopSiteLocationModel->address,
                    'cityArea'      => $cityArea,
                    'statusText'    => OpenShopSiteLocationModel::CLUE_STATUS_MAP[$openShopSiteLocationModel->clueStatus],
                    'clueStatus'    => $openShopSiteLocationModel->clueStatus,
                    'recommender'   => '',
                    'userId'        => $openShopSiteLocationModel->createdByUid,
                    'shopGrade'     => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$openShopSiteLocationModel->shopGrade] ?? '',
                    'putTime'       => $openShopSiteLocationModel->putAt ? date('Y-m-d H:i:s', $openShopSiteLocationModel->putAt) : '-',
                    'area'          => $openShopSiteLocationModel->area ? $openShopSiteLocationModel->area . '㎡' : '-',
                    'clueRentMonth' => ceil($openShopSiteLocationModel->clueRent / 12),
                    'clueRentDay'   => ceil($openShopSiteLocationModel->clueRent / 365),
                    'number'        => $openShopSiteLocationModel->orderNo,
                ];
            })->toArray();


        // 获得选址信息
        $siteLocationModel = OpenShopSiteLocationModel::query()
            ->whereIn(
                'id',
                (clone $relationModel)
                    ->where('source', OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
                    ->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM])
                    ->pluck('relationId')
                    ->toArray()
            )
            ->with([
                'signOrderRel',
                'identityCardRel',
                'baseUserInfoRel',
                'mainProcessRel',
            ])
            ->get();

        $siteUserIds = $siteLocationModel->pluck('createdByUid')->toArray();

        $userIds = array_merge($userIds, $siteUserIds);

        $userInfos = []; //用户信息
        $joinTime  = []; //入职时间
        KmsUser::query()
            ->whereIn('rmsUserId', $userIds)
            ->get()
            ->each(function (KmsUser $kmsUser) use (&$userInfos, &$joinTime) {
                if ($kmsUser->rmsUserId != 0) {
                    $userInfos[$kmsUser->rmsUserId] = $kmsUser->nickname . '(' . $kmsUser->name . ')';
                    $joinTime[$kmsUser->rmsUserId]  = $kmsUser->joinTime;
                }
            });

        if ($siteLocationModel->count()) {
            //提交日志
            $submitModel = OpenShopSiteLocationExamineLogModel::query()
                ->whereIn('createdByUid', array_column($siteUserIds, 'id'))
                ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_SITE_FROM_SUBMIT)
                ->withoutGlobalScope('isDel');
            //获得首次提交的订单
            $submitOrderNo = $submitModel->groupBy('createdByUid')
                ->pluck('orderNo')
                ->toArray();

            //获得首次提交的人
            $submitTempCount = [];
            $submitModel->each(function (OpenShopSiteLocationExamineLogModel $openShopSiteLocationExamineLogModel) use (&$submitTempCount) {
                $submitTempCount[] = $openShopSiteLocationExamineLogModel->createdByUid;
            });
            $submitOnlyOneCount = [];
            $tempSubmit         = array_count_values($submitTempCount);
            foreach ($tempSubmit as $userId => $count) {
                if ($count == 1) {
                    $submitOnlyOneCount[] = $userId;
                }
            }

            $siteLocationList = $siteLocationModel->map(function (OpenShopSiteLocationModel $openShopSiteLocationModel) use ($joinTime, $submitOrderNo, $submitOnlyOneCount) {
                $info       = (optional($openShopSiteLocationModel->identityCardRel)->name ?: '-') . ' ' . (optional($openShopSiteLocationModel->signOrderRel)->shopCode ?: '-');
                $cityArea   = $openShopSiteLocationModel->cityArea ?: (optional($openShopSiteLocationModel->baseUserInfoRel)->chooseShopAddressPrefix ?: '-');
                $statusText = OpenShopSiteLocationModel::CN_PROVINCE_STATUS[$openShopSiteLocationModel->siteStatus] ?? '-';
                $status     = $openShopSiteLocationModel->siteStatus;
                $number     = optional($openShopSiteLocationModel->signOrderRel)->shopCode ?: '-'; //编号
                $tag        = '';
                if (in_array($openShopSiteLocationModel->siteStatus, [
                        OpenShopSiteLocationModel::SITE_STATUS_2,
                        OpenShopSiteLocationModel::SITE_STATUS_3,
                        OpenShopSiteLocationModel::SITE_STATUS_4,
                        OpenShopSiteLocationModel::SITE_STATUS_10,
                        OpenShopSiteLocationModel::SITE_STATUS_11,
                        OpenShopSiteLocationModel::SITE_STATUS_20,
                        OpenShopSiteLocationModel::SITE_STATUS_21,
                    ]) || in_array($openShopSiteLocationModel->clueStatus, [
                        OpenShopSiteLocationModel::CLUE_STATUS_3,
                        OpenShopSiteLocationModel::CLUE_STATUS_4,
                        OpenShopSiteLocationModel::CLUE_STATUS_5,
                        OpenShopSiteLocationModel::CLUE_STATUS_6,
                        OpenShopSiteLocationModel::CLUE_STATUS_10,
                        OpenShopSiteLocationModel::CLUE_STATUS_11,
                        OpenShopSiteLocationModel::CLUE_STATUS_13,
                    ])) {
                    if (time() < (($joinTime[$openShopSiteLocationModel->developConsultantId] ?? 0) + 86400 * 60)) {
                        $tag = '新人提交';
                    }

                    if (in_array($openShopSiteLocationModel->orderNo, $submitOrderNo) && in_array($openShopSiteLocationModel->developConsultantId, $submitOnlyOneCount)) {
                        $tag = '首次提交';
                    }
                }

                return [
                    'id'                    => $openShopSiteLocationModel->id,
                    'orderNo'               => $openShopSiteLocationModel->orderNo,
                    'statusText'            => $statusText,
                    'status'                => $status,
                    'cityArea'              => $cityArea,
                    'info'                  => $info,
                    'tag'                   => $tag,
                    'updatedAt'             => $openShopSiteLocationModel->updatedAt->toDateString(),
                    'siteOrClue'            => 0,
                    'number'                => $number,
                    'developConsultantName' => $openShopSiteLocationModel->developConsultantName ?: '待指派开发顾问',
                    'messageFrom'           => $openShopSiteLocationModel->messageFrom,
                    "messageFromText"       => (function ($messageFrom) {
                        $messageFromText = "";
                        switch ($messageFrom) {
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_1:
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_3:
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_7:
                                $messageFromText = "自带址";
                                break;
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_2:
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_6:
                                $messageFromText = "推荐址";
                                break;
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_5:
                                $messageFromText = "转让";
                                break;
                        }
                        return $messageFromText;
                    })(
                        $openShopSiteLocationModel->messageFrom
                    ),
                    'tags'                  => collect(
                        OrderService::getOrderTags(
                            1,
                            SiteLocationService::tagLocationStatus($openShopSiteLocationModel),
                        )
                    )->where('name', '迁')->values(),
                ];
            })->toArray();
        } else {
            $siteLocationList = [];
        }


        return [
            'id'                => $taskModel->id,
            'grade'             => $taskModel->grade,
            'wgName'            => $taskModel->wgName,
            'collect'           => $taskModel->collect,
            'projectPhase'      => $taskModel->projectPhase,
            'projectPhaseStr'   => CustomerDepartmentTaskModel::PROJECT_PHASE_MAPPING[$taskModel->projectPhase] ?? '',
            'collectStr'        => CustomerDepartmentTaskModel::COLLECT_MAPPING[$taskModel->collect] ?? CustomerDepartmentTaskModel::COLLECT_OFF,
            'gradeStr'          => CustomerDepartmentTaskModel::GRADE_MAPPING[$taskModel->grade] ?? '',
            'prefixAddress'     => $taskModel->prefixAddress,
            'address'           => $taskModel->address,
            'assignTime'        => $taskModel->assignTime ? Carbon::createFromTimestamp($taskModel->assignTime)->format('Y-m-d H:i:s') : '-',
            'departmentManager' => $userInfos[$taskModel->assignId] ?? '-',
            'followUpTime'      => $taskModel->followUpTime ? Carbon::createFromTimestamp($taskModel->followUpTime)->toDateTimeString() : '-',
            'kpPartyName'       => $kpPartyName ?: '-',
            'followRecord'      => collect($followRecord)->map(function ($item) use ($userInfos) {
                $item['username'] = $userInfos[$item['userId']] ?? '-';
                return $item;
            })->toArray(),
            'clueRecord'        => collect($clueRecord)->map(function ($item) use ($userInfos) {
                $item['username'] = $userInfos[$item['userId']] ?? '-';
                return $item;
            })->toArray(),
            'addHouseInfo'      => [
                'shopModelType' => SiteLocationEnum::SHOP_MODEL_TYPE_MALL,
                'mallName'      => $taskModel->wgName,
                'mallId'        => $taskModel->siteLocationMallRel->mallId,
                'isWhiteList'   => (bool)count($guanyuanData),
                'mallGrade'     => CustomerDepartmentTaskModel::GRADE_MAPPING[$taskModel->grade] ?? '',
                'mallStatus'    => (bool)$taskModel->siteLocationMallRel->mallStatus,
                'leaseName'     => $kpPartyName ?: '',
                'leaseMobile'   => $kpPartyPhone ?: '',
                'taskId'        => $taskModel->id,
            ],
            'houseList'         => collect($houseList)->map(function ($item) use ($userInfos) {
                $item['recommender'] = $userInfos[$item['userId']];
                return $item;
            })->toArray(),
            'siteList'          => $siteLocationList
        ];
    }


    /**
     * 收藏任务
     * @param int $id
     * @param int $collect
     * @param array $authUser
     * @return bool
     */
    public static function collectTask(int $id, int $collect, array $authUser): bool
    {
        $taskModel = CustomerDepartmentTaskModel::query()
            ->where('id', $id)
            //->where('assignId', ($authUser['userId'] ?? 0))   // 切换指派人不取消收藏状态
            ->first();

        if (null == $taskModel || !in_array($collect, array_keys(CustomerDepartmentTaskModel::COLLECT_MAPPING))) {
            self::throwErr('这不是您的任务或者参数错误', 403);
        }

        $taskModel->timestamps = false;
        $taskModel->collect    = $collect;
        return $taskModel->save();
    }


    /**
     * 跟进记录详情
     * @param int $id
     * @param array $authUser
     * @return array
     */
    public static function detailFollowUp(int $id, array $authUser): array
    {
        $followUpModel = CustomerDepartmentFollowUpRecordModel::query()
            ->where('id', $id)
            ->with([
                'resourceRel', 'kpPartyRel', 'clueRel' => function ($query) {
                    $query->with(['followUpRel']);
                }
            ])
            ->first();

        if (null == $followUpModel) {
            self::throwErr('跟进记录不存在', 404);
        }

        // 文件
        $files = [];
        if (count($followUpModel->resourceRel)) {
            $files = collect($followUpModel->resourceRel)->map(function ($file) {
                return picturePath($file['url']);
            });
        }

        $userIds = [];
        // 关联线索
        $clueRecord = [];
        if (count($followUpModel->clueRel)) {
            $userIds = $followUpModel->clueRel->pluck('createdByUid')->toArray();
            foreach ($followUpModel->clueRel as $clueRel) {
                $firstTime  = '-';
                $lastTime   = '-';
                $lastUserId = 0;
                if (count($clueRel->followUpRel)) {
                    $firstTime  = $clueRel->followUpRel->first()->createdAt->format('Y-m-d');
                    $lastTime   = $clueRel->followUpRel->last()->createdAt->format('Y-m-d');
                    $lastUserId = $userIds[] = $clueRel->followUpRel->last()->createdByUid;
                }
                $clueRecord[] = [
                    'id'        => $clueRel->id,
                    'title'     => Carbon::createFromTimestamp($clueRel->preHaving)->format('预计Y年m月d日出铺'),
                    'firstTime' => $firstTime,
                    'lastTime'  => $lastTime,
                    'logCount'  => count($clueRel->followUpRel),
                    'username'  => '',
                    'userId'    => $lastUserId,
                    'content'   => $clueRel->content,
                    'status'    => $clueRel->status,
                    'statusStr' => CustomerDepartmentClueRecordModel::STATUS_MAPPING[$clueRel->status] ?? '',
                ];
            }
        }

        $userInfos = [];
        KmsUser::query()
            ->whereIn('rmsUserId', $userIds)
            ->get()
            ->each(function (KmsUser $kmsUser) use (&$userInfos) {
                if ($kmsUser->rmsUserId != 0) {
                    $userInfos[$kmsUser->rmsUserId] = $kmsUser->nickname . '(' . $kmsUser->name . ')';
                }
            });

        return [
            'type'            => $followUpModel->type,
            'typeStr'         => CustomerDepartmentFollowUpRecordModel::TYPE_MAPPING[$followUpModel->type] ?? '',
            'method'          => $followUpModel->method,
            'methodStr'       => CustomerDepartmentFollowUpRecordModel::METHOD_MAPPING[$followUpModel->method] ?? '',
            'content'         => $followUpModel->content,
            'time'            => $followUpModel->createdAt->toDateTimeString(),
            'kpPartyUsername' => (string)optional($followUpModel->kpPartyRel)->name,
            'kpPartyPhone'    => (string)optional($followUpModel->kpPartyRel)->phone ? substr_replace(optional($followUpModel->kpPartyRel)->phone, '****', 3, 4) : '',
            'files'           => $files,
            'clueRecord'      => collect($clueRecord)->map(function ($item) use ($userInfos) {
                $item['username'] = $userInfos[$item['userId']];
                return $item;
            })->toArray(),
            'relationHouse'   => [
                // todo 关联房源
            ]
        ];
    }


    /**
     * 客户详情
     * @param $id
     * @param $authUser
     * @return array
     */
    public static function detailDock($id, $authUser): array
    {
        $dockModel = CustomerDepartmentKpPartyRecordModel::query()
            ->where('id', $id)
            ->first();

        if (null == $dockModel) {
            self::throwErr('客服不存在', 404);
        }

        return [
            'name'           => $dockModel->name,
            'phone'          => $dockModel->phone,
            'wechatCode'     => $dockModel->wechatCode,
            'gender'         => $dockModel->gender,
            'type'           => $dockModel->type,
            'typeStr'        => CustomerDepartmentKpPartyRecordModel::TYPE_MAPPING[$dockModel->type] ?? '',
            'genderStr'      => CustomerDepartmentKpPartyRecordModel::GENDER_MAPPING[$dockModel->gender] ?? '',
            'position'       => $dockModel->position,
            'prefixAddress'  => $dockModel->prefixAddress,
            'provinceCode'   => $dockModel->provinceCode,
            'cityCode'       => $dockModel->cityCode,
            'districtCode'   => $dockModel->districtCode,
            'company'        => $dockModel->company,
            'companyType'    => $dockModel->companyType,
            'companyTypeStr' => CustomerDepartmentKpPartyRecordModel::COMPANY_TYPE_MAPPING[$dockModel->companyType] ?? '',
            'onTheJob'       => $dockModel->onTheJob,
            'onTheJobStr'    => CustomerDepartmentKpPartyRecordModel::IS_ON_THE_JOB_MAPPING[$dockModel->onTheJob] ?? '',
            'remark'         => $dockModel->remark,
        ];
    }


    /**
     * 根据任务ID调整项目进度
     * @param $taskId
     * @return int
     */
    public static function getProjectPhaseByTaskId($taskId): int
    {
        $taskModel = CustomerDepartmentTaskModel::query()
            ->where('id', $taskId)
            ->first();

        if (in_array($taskModel->projectPhase, [CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM])) {
            return $taskModel->projectPhase;
        }

        $clueRes = CustomerDepartmentClueRecordModel::query()
            ->where('taskId', $taskId)
            ->whereIn('status', [CustomerDepartmentClueRecordModel::STATUS_FOLLOWING_UP, CustomerDepartmentClueRecordModel::STATUS_COMPLETE])
            ->exists();

        return $clueRes ? CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE : CustomerDepartmentTaskModel::PROJECT_PHASE_NO_CLUE;
    }


    /**
     * 完成阶段修改勘址任务状态
     * @param $source
     * @param $relationId
     * @param $siteStatus
     * @return bool
     */
    public static function updateTaskProjectPhaseBySite($source, $relationId, $siteStatus): bool
    {
        // 添加绑定关系
        $binding   = self::bindSiteTask($relationId);

        // 修改勘址任务状态
        $taskId = (int)CustomerDepartmentSiteLocationRelationModel::query()
            ->where('relationId', $relationId)
            ->value('taskId');

        $taskModel = CustomerDepartmentTaskModel::query()
            ->where('id', $taskId)
            ->first();

        if (null == $taskModel) {
            return false;
        }

        $oldProjectPhase = $taskModel->projectPhase;

        $projectPhase = 0;

        switch ($source) {
            case OpenShopSiteLocationModel::SOURCE_OPEN_SHOP:
                if ($siteStatus == OpenShopSiteLocationModel::SITE_STATUS_21) {
                    $taskModel->projectPhase = $projectPhase = CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION;

                    // 达成合作
                    $phone = (string)OpenShopSiteLocationModel::query()
                        ->where('id', $relationId)
                        ->value('leaseMobile');

                    CustomerDepartmentKpPartyRecordModel::query()
                        ->where('phone', $phone)
                        ->update([
                            'cooperate' => CustomerDepartmentKpPartyRecordModel::COOPERATE_ON
                        ]);

                }
                if ($siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4) {
                    $taskModel->projectPhase = $projectPhase = CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM;
                }
                break;
            case OpenShopSiteLocationModel::SOURCE_HOUSING:
                if (!in_array($taskModel->projectPhase, [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM])) {
                    $taskModel->projectPhase = $projectPhase = CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE;
                }
                break;
            default:
                return false;
        }

        if ($projectPhase) {
            CustomerDepartmentSiteLocationRelationModel::query()
                ->where('relationId', $relationId)
                ->where('source', $source)
                ->update([
                    'projectPhase' => $projectPhase
                ]);

            CustomerDepartmentOperationLogModel::addLog($taskId, '项目阶段变更', [
                [
                    'theme' => '项目阶段变更',
                    'data'  => [
                        [
                            'key'         => 'orderNo',
                            'beforeValue' => $oldProjectPhase,
                            'afterValue'  => $projectPhase,
                            'beforeText'  => CustomerDepartmentTaskModel::PROJECT_PHASE_MAPPING[$oldProjectPhase] ?? '',
                            'afterText'   => CustomerDepartmentTaskModel::PROJECT_PHASE_MAPPING[$projectPhase] ?? '',
                            'type'        => 1,
                            'description' => '编号变更',
                        ]
                    ]
                ]
            ], $taskModel->assignId);
        }
        $taskModel->save();

        Artisan::call("siteLocation:sync-development-manager-task-info --rmsUserIds={$taskModel->assignId}");

        return true;
    }


    /**
     * 房源上架后更新绑定关系
     * @param $siteLocationId
     * @return bool
     */
    public static function bindSiteTask($siteLocationId): bool
    {

        $siteLocationModel = OpenShopSiteLocationModel::query()
            ->where('id', $siteLocationId)
            ->first();

        if (!$siteLocationModel->mallId || $siteLocationModel->source != OpenShopSiteLocationModel::SOURCE_HOUSING) {
            return false;
        }

        // 根据mallID获得wgNumber
        $wgNumber = (string)SiteLocationMallModel::query()
            ->where('mallId', $siteLocationModel->mallId)
            ->value('wgNumber');

        if (!$wgNumber) {
            return false;
        }

        // 获得勘址任务
        $siteTaskModel = CustomerDepartmentTaskModel::query()
            ->where('wgNumber', $wgNumber)
            ->first();

        if ($siteTaskModel == null || $siteLocationModel->developConsultantId != $siteTaskModel->assignId) {
            return false;
        }

        $siteTaskRelationModel = CustomerDepartmentSiteLocationRelationModel::query()
            ->updateOrCreate([
                'relationNumber' => $siteLocationModel->orderNo,
                'relationId'     => $siteLocationModel->id,
                'taskId'         => $siteTaskModel->id,
                'source'         => OpenShopSiteLocationModel::SOURCE_HOUSING,
            ]);

        $siteTaskRelationModel->projectPhase = CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE;
        $siteTaskRelationModel->createdAt    = time();
        $siteTaskRelationModel->updatedAt    = time();
        $siteTaskRelationModel->createdByUid = $siteLocationModel->developConsultantId;
        $siteTaskRelationModel->updatedByUid = $siteLocationModel->developConsultantId;
        $siteTaskRelationModel->save();
        return true;
    }

}
